<template>
  <div class="box">
    <!-- 查询项 -->
    <div class="query-params long-label">
      <el-form :model="searchParams"
               :inline="true"
               label-width="80px"
               ref="queryForm"
               size="small">
        <el-form-item label="年份">
          <el-date-picker v-model="searchParams.year"
                          type="year"
                          placeholder="请选择"
                          value-format="yyyy"
                          class="form-content-width">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="行政区划">
          <el-select clearable
                     filterable
                     class="form-content-width"
                     v-model="searchParams.adCd"
                     placeholder="请选择">
            <el-option v-for="item in districtOptions"
                       :key="item.adCd"
                       :label="item.adNm"
                       :value="item.adCd">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建立时间">
          <el-date-picker v-model="searchParams.printTime"
                          type="month"
                          placeholder="选择时间"
                          class="form-content-width"
                          value-format="yyyy-MM"
                          :clearable="true"
                          :editable="false">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select clearable
                     filterable
                     class="form-content-width"
                     v-model="searchParams.status"
                     placeholder="请选择">
            <el-option v-for="item in statusOptions"
                       :key="item.dictValue"
                       :label="item.dictLabel"
                       :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="协调机制文件名称">
          <el-input placeholder="请输入"
                    v-model.trim="searchParams.cooMecFile"
                    class="form-content-width"></el-input>
        </el-form-item>
        <el-form-item label="协调机制类型">
          <el-select clearable
                     filterable
                     class="form-content-width"
                     v-model="searchParams.cooMecType"
                     placeholder="请选择">
            <el-option v-for="item in cooMecTypeOptions"
                       :key="item.dictValue"
                       :label="item.dictLabel"
                       :value="item.dictValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文号">
          <el-input placeholder="请输入"
                    v-model.trim="searchParams.fileNum"
                    class="form-content-width"></el-input>
        </el-form-item>
        <el-form-item class="form-btn-item">
          <el-button type="primary"
                     size="mini"
                     @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 权限按钮栏 -->
    <button-row :permiList="permiList"
                @dialogShow="dialogShow"></button-row>

    <!-- 表格 -->
    <div class="table-item">
      <el-table ref="multipleTable"
                :data="tableData"
                v-loading="tableLoading"
                border
                highlight-current-row
                @row-click="handleTableRowClick"
                @selection-change="handleSelectionChange"
                class="w100p"
                height="59vh">
        <el-table-column type="selection"
                         width="46"
                         align="center" />
        <el-table-column prop="statusNm"
                         label="审核状态"
                         width="100"
                         header-align="center">
          <template slot-scope="{row}">
            <span :class="getStatusTextColor(row.status)">{{row.statusNm}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="year"
                         label="年份"
                         width="80"
                         align="center" />
        <el-table-column prop="adCdNm"
                         label="区县"
                         min-width="120"
                         header-align="center"
                         show-overflow-tooltip />
        <el-table-column prop="cooMecTypeList"
                         label="协调机制类型"
                         min-width="120"
                         header-align="center"
                         show-overflow-tooltip />
        <el-table-column prop="cooMecFile"
                         label="协调机制文件名称"
                         min-width="120"
                         header-align="center"
                         show-overflow-tooltip />
        <el-table-column prop="fileNum"
                         label="文号"
                         min-width="100"
                         header-align="center"
                         show-overflow-tooltip />
        <el-table-column prop="printTime"
                         label="建立时间"
                         min-width="100"
                         header-align="center"
                         show-overflow-tooltip>
          <template slot-scope="{row}">
            {{formatDateText(row.printTime)}}
          </template>
        </el-table-column>
        <el-table-column label="协调机制负责人召集人"
                         header-align="center">
          <el-table-column prop="dutyName"
                           label="姓名"
                           min-width="100"
                           header-align="center"
                           show-overflow-tooltip />
          <el-table-column prop="dutyUnitNm"
                           label="所在单位"
                           header-align="center"
                           min-width="100"
                           show-overflow-tooltip />
          <el-table-column prop="dutyJob"
                           label="党政职务"
                           min-width="100"
                           header-align="center"
                           show-overflow-tooltip />
        </el-table-column>
        <el-table-column prop="memberUnitList"
                         label="成员单位"
                         min-width="120"
                         header-align="center"
                         show-overflow-tooltip />
        <el-table-column prop="remark"
                         label="备注"
                         min-width="120"
                         header-align="center"
                         show-overflow-tooltip />
        <el-table-column prop="downPath"
                         label="附件"
                         min-width="80"
                         align="center">
          <template slot-scope="{row}">
            <el-button type="text"
                       v-show="row.downPath"
                       @click="downLoadAttachment(row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-item">
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="pageNum"
                     :page-sizes="pageSizes"
                     :page-size="pageSize"
                     layout="total, prev, pager, next, sizes"
                     :total="tableTotal">
      </el-pagination>
    </div>

    <!-- 新增编辑 -->
    <Add-edit-mechanism-setUp ref="AddEditMechanismSetUp"
                              :cooMecTypeOptions="cooMecTypeOptions"></Add-edit-mechanism-setUp>

    <!-- 导入 -->
    <Import-excel-file ref="ImportExcelFile"
                       :uploadUrl="uploadImgUrl"
                       :childCode="menuCode"
                       @importSuccess="importSuccess"
                       @importError="importError"></Import-excel-file>

    <!-- 批量审核 -->
    <Water-save-batch-audit ref="WaterSaveBatchAudit"
                            @auditSubmit="handleBatchAuditSubmit"></Water-save-batch-audit>

    <!-- 批量退回 -->
    <Water-save-batch-back ref="WaterSaveBatchBack"
                           @backSubmit="handleBatchBackSubmit"></Water-save-batch-back>
  </div>
</template>

<script>
import WaterSaveBatchAudit from '@/views/businessManagement/waterUseEfficiencyControl/components/batch-audit';
import WaterSaveBatchBack from '@/views/businessManagement/waterUseEfficiencyControl/components/batch-back';
import ImportExcelFile from '@/components/ImportExcelFile/index';
import AddEditMechanismSetUp from './components/add-edit-mechanism-setUp';
import { coordinationMechanismSetUpList, delCoordinationMechanismSetUp, auditCoordinationMechanismSetUp } from '@/api/businessManagement/waterUseEfficiencyControl/waterSaveManagement/coordinationMechanism/coordinationMechanismSetUpTable';
import { pagePermissionMixin } from '@/mixins/pagePermissionMixin.js';
import { tableMixin } from '@/mixins/tableMixin.js';
import { districtOptionsMixin } from '@/mixins/districtOptionsMixin.js';
import ButtonRow from '@/components/ButtonRow/index';
import dayjs from "dayjs";
export default {
  mixins: [tableMixin, pagePermissionMixin, districtOptionsMixin],
  components: {
    ButtonRow,
    AddEditMechanismSetUp,
    ImportExcelFile,
    WaterSaveBatchAudit,
    WaterSaveBatchBack
  },
  data() {
    return {
      searchParams: {
        year: '',
        printTime: '', // 建立时间
        adCd: '', // 行政区划
        status: '', // 审核状态
        cooMecFile: '', // 协调机制文件名称
        fileNum: '', // 文号
        cooMecType: '', // 协调机制类型
      },
      statusOptions: [ // 审核状态选项
        { dictLabel: '未审核', dictValue: '1' },
        { dictLabel: '审核通过', dictValue: '2' },
        { dictLabel: '审核未通过', dictValue: '3' },
      ],
      cooMecTypeOptions: [], // 协调机制类型选项
    }
  },
  computed: {
    uploadImgUrl() {
      return process.env.VUE_APP_BASE_API + `/api/mechanism/importExcel`
    },
    // 格式化时间显示
    formatDateText() {
      return function (time) {
        if (!time) return '';
        return dayjs(time).format('YYYY年MM月')
      }
    }
  },
  created() {
    this.getPagePermis();
    this.getPageOptionsData();
  },
  mounted() {
    // this.searchParams.printTime = dayjs().format('YYYY-MM');
    if (this.userAdCd != '500000') {
      this.searchParams.adCd = this.userAdCd
    }
    this.search();
  },
  methods: {
    // 获取页面选项数据
    getPageOptionsData() {
      Promise.all([
        this.getDicts('COORDINATING_MECHANISM_TYPE'),
        this.getDicts('AUDIT_STATUS_TYPE')
      ]).then(resList => {
        let [cooMecTypeOptionsData, statusOptionsData] = resList;
        // 协调机制类型选项
        if (cooMecTypeOptionsData.status == 200) {
          this.cooMecTypeOptions = cooMecTypeOptionsData.data;
        }
        // 审核状态选项
        if (statusOptionsData.status == 200) {
          this.statusOptions = statusOptionsData.data;
        }
      })
    },
    async search() {
      this.tableLoading = true; // 开启加载效果
      let { searchParams, pageSize, pageNum } = this;
      let params = { ...searchParams, pageIndex: pageNum, pageSize };
      // console.log(params);
      let { status, data } = await coordinationMechanismSetUpList(params);
      if (status == 200) {
        this.tableData = data.list;
        this.tableTotal = data.total;
      }
      this.tableLoading = false;
    },
    // 权限按钮栏
    dialogShow(val) {
      let key = val.type
      // console.log(key)
      switch (key) {
        case 'Add':
          this.openAddDialog();
          break;
        case 'Edit':
          this.openEditViewDialog('edit');
          break;
        case 'Delete':
          this.handleDelete();
          break;
        case 'View':
          this.openEditViewDialog('view');
          break;
        case "Download":
          this.$utils.exportExcel('api/mechanism/downTemplate', {})
          break;
        case 'ImportExcel':
          this.$refs.ImportExcelFile.open();
          break;
        case "ExprotExcel":
          this.exportTableData();
          break;
        case 'Examine':
          this.openEditViewDialog('audit');
          break;
        case "AuditAll":
          this.openBatchAuditDialog();
          break;
        case "back":
          this.openEditViewDialog('back');
          break;
        case "backAll":
          this.openBatchBackDialog();
          break;
        default:
          break;
      }
    },
    // 新增弹窗
    openAddDialog() {
      this.$refs.AddEditMechanismSetUp.open()
    },
    // 编辑、查看、审核弹窗
    openEditViewDialog(opType) {
      if (this.multipleSelection.length !== 1) {
        this.unselectedAlert();
        return false
      }

      // 已审核不能再进行审核
      if (opType === 'audit' && this.multipleSelection[0].status == '2') {
        this.unselectedAlert('该信息已审核通过，不能再次审核！');
        return false
      }

      // 审核通过不能再编辑。市局用户可以编辑
      if (opType === 'edit' && this.userAdCd != '500000' && this.multipleSelection[0].status === '2') {
        this.unselectedAlert('该信息已审核通过，不能编辑修改！');
        return false
      }

      // 退回，未审核不能退回
      if (opType === 'back' && this.multipleSelection[0].status === '1') {
        this.unselectedAlert('该信息未审核，不能退回！');
        return false
      }

      this.$refs.AddEditMechanismSetUp.open(this.multipleSelection[0], opType);
    },
    // 删除
    handleDelete() {
      if (this.multipleSelection.length === 0) {
        this.unselectedAlert();
        return false
      }
      // 判断选中的审核状态是否都为未审核，未审核才能删除。 市局用户可以删除所有状态
      let auditFlag = this.multipleSelection.every(item => item.status === '1');
      if (this.userAdCd != '500000' && !auditFlag) {
        this.unselectedAlert('选中数据包含有已审核信息，只能删除未审核的信息！！');
        return false
      }

      this.$confirm(`是否删除选中的台账信息？`, '提示', {
        type: 'warning'
      }).then(async () => {
        let params = {
          id: this.multipleSelection.map(item => item.id).join(',') // 主键id集合转字符串
        };
        // console.log(params)
        let { status, errors } = await delCoordinationMechanismSetUp(params);
        if (status == 200) {
          this.msgSuccess("操作成功");
          this.search();
        } else {
          this.msgError(`错误${status}：${errors[0].message}`);
        }
      })
    },
    // 批量审核弹窗
    openBatchAuditDialog() {
      if (this.multipleSelection.length === 0) {
        this.unselectedAlert('请选择一条或多条记录进行操作！');
        return false
      }

      // 判断选中的审核状态是否有已审核
      let auditFlag = this.multipleSelection.some(item => item.status === '2');
      if (auditFlag) {
        this.unselectedAlert('选中数据包含有已审核信息，请重新选择！');
        return false
      }

      // 选中1个
      if (this.multipleSelection.length === 1) {
        this.$refs.AddEditMechanismSetUp.open(this.multipleSelection[0], 'audit');
      } else { // 选中多个
        this.$refs.WaterSaveBatchAudit.open()
      }
    },
    // 提交批量审核
    async handleBatchAuditSubmit(auditData) {
      let params = { ...auditData }
      params.idList = this.multipleSelection.map(item => item.id).join(',')
      let { status, errors } = await auditCoordinationMechanismSetUp(params)
      if (status == 200) {
        this.msgSuccess('操作成功');
        this.search();
      } else {
        this.msgError(`错误${status}：${errors[0].message}`)
      }
    },
    // 批量退回弹窗
    openBatchBackDialog() {
      if (this.multipleSelection.length === 0) {
        this.unselectedAlert('请选择一条或多条记录进行操作！');
        return false
      }

      // 判断选中的审核状态是否有未审核
      let backFlag = this.multipleSelection.some(item => item.status === '1');
      if (backFlag) {
        this.unselectedAlert('选中数据包含有未审核信息，请重新选择！');
        return false
      }

      // 选中1个
      if (this.multipleSelection.length === 1) {
        this.$refs.AddEditMechanismSetUp.open(this.multipleSelection[0], 'back');
      } else { // 选中多个
        this.$refs.WaterSaveBatchBack.open()
      }
    },
    // 提交批量退回
    handleBatchBackSubmit(backData) {
      this.handleBatchAuditSubmit(backData)
    },
    // 导出表格数据
    exportTableData() {
      let { searchParams, pageSize, pageNum } = this;
      let params = { ...searchParams, pageIndex: pageNum, pageSize };
      // console.log(params)
      this.$utils.exportExcel('/api/mechanism/export', params)
    },
    // 导入成功，重新请求数据
    importSuccess() {
      this.search()
    },
    // 导入数据部分成功或未成功，提示报错，并下载错误信息文件
    importError(errMsg) {
      // console.log(errMsg)
      this.search()
      this.openDownFileAlert(errMsg, '/api/mechanism/exportFailList')
    },
    // 下载附件
    downLoadAttachment(row) {
      let url = row.downPath
      if (url) {
        this.$utils.downloadFile(url)
      }
    }
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/table-page.scss";
/deep/.el-table--border th:nth-of-type(1) {
  border-left: 1px solid #b0dff0;
}
.query-params {
  /deep/.form-content-width {
    width: 200px;
  }
}
</style>